'
' *   WakeOnLAN - Wake On LAN
' *    Copyright (C) 2004-2018 Aquila Technology, LLC. <webmaster@aquilatech.com>
' *
' *    This file is part of WakeOnLAN.
' *
' *    WakeOnLAN is free software: you can redistribute it and/or modify
' *    it under the terms of the GNU General Public License as published by
' *    the Free Software Foundation, either version 3 of the License, or
' *    (at your option) any later version.
' *
' *    WakeOnLAN is distributed in the hope that it will be useful,
' *    but WITHOUT ANY WARRANTY; without even the implied warranty of
' *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
' *    GNU General Public License for more details.
' *
' *    You should have received a copy of the GNU General Public License
' *    along with WakeOnLAN.  If not, see <http://www.gnu.org/licenses/>.
' 


'
' *    This module originated from https://autoupdaterdotnet.codeplex.com/
' 


Imports System.ComponentModel
Imports System.Net.Cache
Imports System.Windows.Forms
Imports System.Net
Imports System.IO
Imports System.Diagnostics

Public Class DownloadUpdateDialog
    Private ReadOnly _downloadURL As String

    Private _tempPath As String
    Sub New()
        InitializeComponent()
    End Sub
    Public Sub New(ByVal downloadURL As String)
        InitializeComponent()
        _downloadURL = downloadURL
    End Sub

    Private Sub DownloadUpdateDialogLoad(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim webClient As New System.Net.WebClient()
        Dim uri As New Uri(_downloadURL)
        _tempPath = String.Format("{0}{1}", Path.GetTempPath(), GetFileName(_downloadURL))
        AddHandler webClient.DownloadProgressChanged, AddressOf OnDownloadProgressChanged
        AddHandler webClient.DownloadFileCompleted, AddressOf OnDownloadComplete
        webClient.DownloadFileAsync(uri, _tempPath)
    End Sub

    Private Sub OnDownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs)
        progressBar.Value = e.ProgressPercentage
    End Sub

    Private Sub OnDownloadComplete(sender As Object, e As AsyncCompletedEventArgs)
        Dim processStartInfo = New ProcessStartInfo() With { _
         .FileName = _tempPath, _
         .UseShellExecute = True _
        }
        Process.Start(processStartInfo)
        If Application.MessageLoop Then
            Application.Exit()
        Else
            Environment.Exit(1)
        End If
    End Sub

    Private Shared Function GetFileName(url As String) As String
        Dim fileName = String.Empty

        Dim httpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
        httpWebRequest.CachePolicy = New HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore)
        httpWebRequest.UserAgent = "AutoUpdater"
        httpWebRequest.Method = "HEAD"
        httpWebRequest.AllowAutoRedirect = True
        Dim httpWebResponse = DirectCast(httpWebRequest.GetResponse(), HttpWebResponse)
        If httpWebResponse.StatusCode.Equals(HttpStatusCode.Redirect) OrElse httpWebResponse.StatusCode.Equals(HttpStatusCode.Moved) OrElse httpWebResponse.StatusCode.Equals(HttpStatusCode.MovedPermanently) Then
            If httpWebResponse.Headers("Location") IsNot Nothing Then
                Dim location = httpWebResponse.Headers("Location")
                fileName = GetFileName(location)
                Return fileName
            End If
        End If
        If httpWebResponse.Headers("content-disposition") IsNot Nothing Then
            Dim contentDisposition = httpWebResponse.Headers("content-disposition")
            If Not String.IsNullOrEmpty(contentDisposition) Then
                Const lookForFileName As String = "filename="
                Dim index = contentDisposition.IndexOf(lookForFileName, StringComparison.CurrentCultureIgnoreCase)
                If index >= 0 Then
                    fileName = contentDisposition.Substring(index + lookForFileName.Length)
                End If
                If fileName.StartsWith("""") AndAlso fileName.EndsWith("""") Then
                    fileName = fileName.Substring(1, fileName.Length - 2)
                End If
            End If
        End If
        If String.IsNullOrEmpty(fileName) Then
            Dim uri = New Uri(url)

            fileName = Path.GetFileName(uri.LocalPath)
        End If
        Return fileName
    End Function

End Class
